<template>
  <div class="sellOrderDetail ">
    <a-spin :spinning="loading">
      <a-alert banner :show-icon="false" class="banner">
        <div slot="message" class="flex-between">
          <div class="orderCode">
            订单编号：
            <span>{{ orderDetail.orderCode }}</span>
            <c-button
              class="reloadOrder"
              type="success"
              size="small"
              shape="round"
              @click="reload"
              ><a-icon type="reload" style="fontSize: 12px;"></a-icon>
              刷新</c-button
            >
          </div>
          <div class="createDate">{{ $getTime(orderDetail.createDate) }}</div>
        </div>
      </a-alert>
      <div class="layout-content">
        <div class="header">
          <a-row>
            <a-col :span="12">
              <div class="header-l">
                <p class="companyName">
                  <span>交易对象：</span>
                  <a-tag :color="isSeller() ? 'blue' : 'orange'"
                    >{{ isSeller() ? "销售" : "采购" }}
                  </a-tag>
                  <span class="desc">
                    {{ companyData && companyData.companyName }}
                  </span>
                </p>
                <p class="status">
                  <span class="label">订单状态：</span>
                  <template v-if="isLine()">
                    <LineOrderStatus :data="orderDetail" />
                  </template>
                  <template v-else>
                    <OrderStatus :data="orderDetail" />
                    <template
                      v-if="
                        isSeller() &&
                          orderDetail.orderStatus ===
                            orderDict.pricingStatus.applyModifyPrice.value
                      "
                    >
                      <span class="danger"
                        >申请改价为{{ orderDetail.alterTargetPrice }}</span
                      >
                    </template>
                  </template>
                </p>
                <a-alert
                  message="订单关闭理由："
                  :description="orderDetail.closeRemark"
                  type="error"
                  show-icon
                  v-if="
                    orderDetail.orderStatus ===
                      orderDict.pricingStatus.sellerClose.value ||
                      orderDetail.orderStatus ===
                        orderDict.pricingStatus.buyerClose.value ||
                      orderDetail.orderStatus ===
                        orderDict.pricingStatus.closed.value
                  "
                />
              </div>
            </a-col>
            <a-col :span="12">
              <div class="header-r">
                <template v-if="isLine()">
                  <HandleBtnLine
                    :data="orderDetail"
                    type="detail"
                    @handleSuccess="handleSuccess"
                  />
                </template>
                <template v-else>
                  <p>
                    <HandleBtn
                      :data="orderDetail"
                      type="detail"
                      @handleSuccess="handleSuccess"
                    />
                  </p>
                  <Hedge
                    :data="orderDetail"
                    @handleSuccess="handleSuccess"
                    v-if="ableTransitionHedge"
                  />
                </template>
              </div>
            </a-col>
          </a-row>
        </div>
      </div>
      <div class="layout-content contents">
        <div
          class="content-item"
          v-if="orderDetail.priceType === quotationDict.priceType.pricing.value"
        >
          <a-card title="点价详情" size="small">
            <c-desc :data="orderDetail" :column="2" :columns="pricingColumns">
              <template v-slot:basePrice>
                <span :class="orderDetail.isBasePriceChanged ? 'danger' : ''">
                  {{ orderDetail.basePrice }}
                </span>
                <span class="danger" v-if="orderDetail.isBasePriceChanged">
                  (修改后)
                </span>
                <span
                  class="danger"
                  v-if="
                    orderDetail.orderStatus ===
                      orderDict.pricingStatus.sellerModifyBasePrice.value ||
                      orderDetail.orderStatus ===
                        orderDict.pricingStatus.sellerModifyFirmPrice.value
                  "
                >
                  (修改为：{{ sellerModifyPrice }})
                </span>
              </template>
              <template v-slot:amount>
                <span>{{ orderDetail.amount }}</span>
                <span class="ton">吨</span>
              </template>
              <template v-slot:dealAmount>
                <span>{{ orderDetail.dealAmount }}</span>
                <span class="ton">吨</span>
              </template>
              <template v-slot:customerUser>
                <span
                  >{{ orderDetail.customerCompany.companyNickname }} -
                  {{ orderDetail.customerUser.realName }}</span
                >
              </template>
              <template v-slot:dealStatus>
                <span
                  >{{
                    $getEnum(orderDict.dealStatus, orderDetail.orderDealType)
                  }}
                </span>
              </template>
            </c-desc>
          </a-card>
        </div>
        <div class="content-item">
          <GoodsInfo
            :key="orderDetail.id + orderDetail.version"
            ref="goodsInfo"
            :orderDetail="orderDetail"
            :relevanceInventoryList="relevanceInventoryList"
            v-if="orderDetail.id"
            @handleSuccess="handleSuccess"
          />
        </div>
        <div class="content-item">
          <Inventory
            ref="inventory"
            :orderData="orderDetail"
            v-if="orderDetail.id"
            @relationSuccess="relationSuccess"
            @relevanceInventory="relevanceInventory"
          />
        </div>
        <div class="content-item">
          <a-card title="订单金额" size="small">
            <c-desc :data="orderDetail" :column="2" :columns="priceInfo">
              <template v-slot:dealAmount>
                <span>{{ orderDetail.dealAmount }}</span>
                <span class="ton">吨</span>
              </template>
              <template v-slot:priceType>
                <span
                  >{{
                    $getEnum(quotationDict.priceType, orderDetail.priceType)
                  }}
                </span>
                <span
                  v-if="
                    orderDetail.priceType ===
                      quotationDict.priceType.pricing.value
                  "
                >
                  <span>（{{ orderDetail.futuresContract }}</span>
                  <i>+</i>
                  <span>{{ orderDetail.premium }}）</span>
                </span>
              </template>
              <template v-slot:tax>
                <span
                  v-if="
                    orderDetail.priceType ===
                      quotationDict.priceType.pricing.value
                  "
                  >{{
                    Number(orderDetail.basePrice) + Number(orderDetail.premium)
                  }}
                </span>
                <span v-else>{{ orderDetail.firmPrice }}</span>
                <span
                  class="danger"
                  v-if="
                    (orderDetail.orderStatus ===
                      orderDict.pricingStatus.sellerModifyBasePrice.value ||
                      orderDetail.orderStatus ===
                        orderDict.pricingStatus.sellerModifyFirmPrice.value) &&
                      orderDetail.priceType ===
                        quotationDict.priceType.confirm.value
                  "
                >
                  (修改为：{{ sellerModifyPrice }})
                </span>
              </template>
              <template v-slot:slidePriceType>
                <span
                  >{{
                    $getEnum(
                      quotationDict.detailPriceType,
                      orderDetail.slidePriceType
                    )
                  }}
                </span>
              </template>
            </c-desc>
          </a-card>
        </div>
        <div class="content-item">
          <div class="flex-between">
            <div class="info-buyer">
              <a-card title="买家信息" size="small">
                <c-desc :data="buyerCompany" :column="1" :columns="buyerInfo">
                </c-desc>
              </a-card>
            </div>
            <div class="info-seller">
              <a-card title="卖家信息" size="small">
                <c-desc :data="sellerCompany" :column="1" :columns="sellerInfo">
                </c-desc>
              </a-card>
            </div>
          </div>
        </div>
      </div>
      <div class="layout-content contents">
        <Record
          :orderData="orderDetail"
          :key="orderDetail.id + orderDetail.version"
          v-if="orderDetail.id"
        />
      </div>
    </a-spin>
  </div>
</template>

<script>
import {
  // getPurchaseOrderDetail,
  // getSalesOrderDetail
  getOrderDetail
} from "@/api/order";
import {
  // getproviderlineorderdetail,
  // getcustomerlineorderdetail
  getlineorderdetail
} from "@/api/order-line";
import {
  providerqueryorderauditdata,
  customerqueryorderauditdata
} from "@/api/order/modifyGoods";
import quotationDict from "@/dict/quotation";
import HandleBtn from "@/components-business/order/handleBtn";
import HandleBtnLine from "@/components-business/order-line/handleBtn-line";
import OrderStatus from "@/components-business/order/status";
import LineOrderStatus from "@/components-business/order-line/status";
import { isSeller, isBuyer, isLine } from "@/util/common";
import Inventory from "./components/inventory";
import GoodsInfo from "./components/goodsInfo";
import Record from "./components/record";
import Hedge from "./components/hedge";
import orderDict from "@/dict/order";
import { mapState } from "vuex";

const pricingColumns = [
  {
    label: "合约",
    prop: "futuresContract"
  },
  {
    label: "基价",
    prop: "basePrice",
    slot: "basePrice"
  },
  {
    label: "成交量",
    prop: "dealAmount",
    slot: "dealAmount"
  },
  {
    label: "成交状态",
    slot: "dealStatus"
  },
  {
    label: "下单数量",
    prop: "amount",
    slot: "amount"
  },
  {
    label: "点价人",
    prop: "customerUser",
    slot: "customerUser"
  }
];

const buyerInfo = [
  {
    label: "公司名称",
    prop: "companyName"
  },
  {
    label: "点价用户",
    prop: "realName"
  },
  {
    label: "电话",
    prop: "phone"
  }
];

const sellerInfo = [
  {
    label: "公司名称",
    prop: "companyName"
  },
  {
    label: "报价用户",
    prop: "realName"
  },
  {
    label: "电话",
    prop: "phone"
  }
];

export default {
  components: {
    HandleBtnLine,
    HandleBtn,
    OrderStatus,
    LineOrderStatus,
    Inventory,
    GoodsInfo,
    Record,
    Hedge
  },
  data() {
    return {
      loading: false,
      orderDict,
      quotationDict,
      orderDetail: {}, // 订单详情
      pricingColumns,
      buyerInfo,
      sellerInfo,
      relevanceInventoryList: [], // 已关联的实物库存
      sellerModifyPrice: null // 待生成合同订单，卖家申请修改的价格
    };
  },
  watch: {
    $route(to) {
      let orderListRoute = [
        "buyerPricingOrderDetail",
        "buyerConfirmOrderDetail",
        "sellerPricingOrderDetail",
        "sellerConfirmOrderDetail",
        "sellerPricingLineOrderDetail",
        "sellerConfirmLineOrderDetail",
        "buyerPricingLineOrderDetail",
        "buyerConfirmLineOrderDetail"
      ];
      if (orderListRoute.indexOf(to.name) !== -1) {
        this.init();
      }
    },
    refresh() {
      this.init();
    }
  },
  computed: {
    ...mapState(["order"]),
    refresh() {
      return this.order.refresh;
    },
    // 能否转换套保（已挂单、卖家）
    ableTransitionHedge() {
      let res =
        [
          // orderDict.pricingStatus.wait.value,
          orderDict.pricingStatus.yet.value
        ].indexOf(this.orderDetail.orderStatus) !== -1 && isSeller();
      return res;
    },
    priceInfo() {
      let res = [
        {
          label: "作价方式",
          prop: "priceType",
          slot: "priceType"
        },
        {
          label: "价格类型",
          prop: "slidePriceType",
          slot: "slidePriceType",
          hidden:
            this.orderDetail.priceType !== quotationDict.priceType.pricing.value
        },
        {
          label: "成交数",
          prop: "dealAmount",
          slot: "dealAmount"
        },
        {
          label: "含税单价",
          slot: "tax"
        },
        {
          label: "订单成交总金额",
          prop: "totalDealPrice"
        },
        {
          label: "订单总金额",
          prop: "totalPrice"
        }
      ];
      return res;
    },
    orderInfo() {
      let res = [
        {
          label: "交货方式",
          prop: "deliveryType"
        },
        {
          label: "结算方式",
          prop: "settlementType"
        },
        {
          label: "开票日期",
          prop: "invoiceType"
        },
        {
          label: "订单备注",
          prop: isSeller() ? "providerRemark" : "customerRemark"
        }
      ];
      return res;
    },
    // 交易公司信息
    companyData() {
      let res = this.isBuyer()
        ? this.orderDetail.providerCompany
        : this.orderDetail.customerCompany;
      return res;
    },
    // 买家信息
    buyerCompany() {
      let res;
      res = {
        ...this.orderDetail.customerCompany,
        ...this.orderDetail.customerUser
      };
      return res;
    },
    // 卖家信息
    sellerCompany() {
      let res;
      res = {
        ...this.orderDetail.providerCompany,
        ...this.orderDetail.providerUser
      };
      return res;
    }
  },
  methods: {
    isLine,
    isBuyer,
    isSeller,
    // 查询待生成合同订单，卖家申请修改的价格
    querySellerModifyPrice() {
      if (
        this.orderDetail.orderStatus ===
          this.orderDict.pricingStatus.sellerModifyBasePrice.value ||
        this.orderDetail.orderStatus ===
          this.orderDict.pricingStatus.sellerModifyFirmPrice.value
      ) {
        let request = this.isSeller()
          ? providerqueryorderauditdata
          : customerqueryorderauditdata;
        request({
          orderId: this.orderDetail.id,
          version: this.orderDetail.version
        }).then(res => {
          this.sellerModifyPrice =
            this.orderDetail.priceType ===
            this.quotationDict.priceType.pricing.value
              ? res.basePrice
              : res.firmPrice;
        });
      }
    },
    // 关联实物库存信息
    relevanceInventory(res) {
      this.relevanceInventoryList = res;
    },
    // 刷新订单
    reload() {
      // this.orderDetail.version = 0;
      this.init();
    },
    // 关联实物库存成功回调
    relationSuccess(data) {
      this.handleSuccess({ data: data, type: "relationInventory" });
    },
    // 订单操作后回调
    handleSuccess({ data, type }) {
      // 同意关闭订单时，更新实物库存信息
      if (
        [
          "buyerAcceptPricingClose",
          "buyerAcceptConfirmClose",
          "sellerAcceptPricingClose",
          "sellerAcceptConfirmClose"
        ].indexOf(type) !== -1
      )
        this.$refs.inventory.getInventoryList();
      // 更新订单信息
      if (data) {
        this.orderDetail = Object.assign({}, this.orderDetail, data);
        // 待生成合同-修改价格，
        if (
          this.orderDetail.orderStatus ===
          this.orderDict.pricingStatus.sellerModifyBasePrice.value
        ) {
          this.querySellerModifyPrice();
        }
      } else {
        this.reload();
      }
    },
    clickEvent(event, row) {
      this[event](row);
    },
    // 查询订单详情
    init() {
      this.loading = true;
      let request = this.isLine() ? getlineorderdetail : getOrderDetail;
      let params = {
        orderId: this.isLine() ? undefined : this.$route.query.id,
        id: this.isLine() ? this.$route.query.id : undefined
        // version: this.isLine() ? this.$route.query.v : undefined
      };
      request(params)
        .then(res => {
          this.orderDetail = res;
          // 待生成合同-修改价格状态下，查询申请修改的价格
          this.querySellerModifyPrice();
          // this.getOrderRecord();
          // this.getOrderDealRecord();
        })
        .finally(() => {
          this.loading = false;
        });
    }
  },
  created() {
    let name = this.isLine() ? "lineOrderDetail" : "orderDetail";
    if (this.$storage.s_get(name)) {
      this.orderDetail = this.$storage.s_get(name);
      this.$storage.s_remove(name);
      this.querySellerModifyPrice();
    } else {
      this.init();
    }
  },
  beforeDestroy() {
    this.$storage.s_remove("lineOrderDetail");
    this.$storage.s_remove("orderDetail");
  }
};
</script>

<style lang="scss" scoped>
.sellOrderDetail {
  .reloadOrder {
    margin-left: 20px;
  }
  .ton {
    margin-left: 2px;
  }
  .banner {
    padding: 8px 20px;
    background-color: #fff;
    border-bottom: 1px solid #e8e8e8;
    ::v-deep .ant-alert-message {
      color: var(--primary);
      font-weight: bold;
      font-size: 16px;
    }
  }
  .header-r {
    text-align: right;
  }
  .contents {
    .content-item {
      .info-buyer,
      .info-price {
        padding-right: 15px;
      }
      .info-seller,
      .info-order {
        padding-left: 15px;
      }
    }
    ::v-deep .ant-card-head-title {
      font-size: 16px;
    }
    .content-item:not(:first-child) {
      margin-top: 28px;
    }
  }
}
</style>
